package com.example.reactive.handler;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.security.Principal;
import java.util.Collections;

@Component
public class RouterHandler {

    // 响应式控制器方法
    public Mono<ServerResponse> getUser(ServerRequest serverRequest) {
        // 执行一些业务逻辑
        return ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(Collections.singletonMap("message", "Hello world!"));
    }

    public Mono<ServerResponse> createUser(ServerRequest serverRequest) {
        // 执行一些业务逻辑
        return serverRequest.principal()
                .map(Principal::getName)
                .flatMap((username) ->
                        ServerResponse.ok()
                                .contentType(MediaType.APPLICATION_JSON)
                                .bodyValue(Collections.singletonMap("message", "Hello " + username + "!"))
                );
    }

    public Mono<ServerResponse> updateUser(ServerRequest serverRequest) {
        // 执行一些业务逻辑
        return ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(Collections.singletonMap("message", "Hello world!"));
    }

    public Mono<ServerResponse> deleteUser(ServerRequest serverRequest) {
        // 执行一些业务逻辑
        return ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(Collections.singletonMap("message", "Hello world!"));
    }

}


// 配置参考 https://docs.springjava.cn/spring-framework/reference/web/webflux-functional.html